package org.ssp.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.ssp.util.MyX509TrustMannger;

public class HttpsRequest {
	/**
	 * java发起https请求
	 * @throws IOException
	 * @throws Exception 
	 * @throws NoSuchAlgorithmException 
	 */
	 public static String httpRequest() throws IOException, NoSuchAlgorithmException, Exception {
			URL url=null;
			StringBuffer buffer=null;
			try {
				//增加证书部分
				//创建SSL context
				SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
				TrustManager[] tm={new MyX509TrustMannger()};
				//初始化
				sslContext.init(null, tm,new java.security.SecureRandom());
				//获取sslSocketFactory对象
				SSLSocketFactory ssf=sslContext.getSocketFactory();
				
				url = new URL("https://kyfw.12306.cn");
				HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				//设置当前实例使用的SSLSocketFactory			
				conn.setSSLSocketFactory(ssf);
				conn.connect();

				//读取服务器返回的内容
				InputStream is=conn.getInputStream();
				InputStreamReader isr=new InputStreamReader(is,"utf-8");
				BufferedReader br=new BufferedReader(isr);
				buffer=new StringBuffer();
				String line=null;
				while((line=br.readLine())!=null){
					buffer.append(line);
				}
				//console显示
//				System.out.println(buffer.toString());
				
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			return buffer.toString();

		}

}
